import os
import random
import time
from datetime import datetime
from fastapi import FastAPI, Request, status
from sqlalchemy.dialects.mysql import INTEGER, VARCHAR,JSON
from sqlalchemy import Column
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel
from db.mysql import DBSession
from vendor.extend.deepseek_pdf_generator import DeepSeekPDFGenerator

Base = declarative_base()

class GroundReport(Base):
    __tablename__ = 'ground_report'

    id = Column(INTEGER, primary_key=True)
    prompt = Column(VARCHAR(3000), default='', nullable=False)
    content = Column(VARCHAR(10000), default='', nullable=False)
    http_path = Column(VARCHAR(255), default='', nullable=False)
    file_path = Column(VARCHAR(255), default='', nullable=False)
    create_time = Column(INTEGER, default=0)
    update_time = Column(INTEGER, default=0)


class FormBody(BaseModel):
    mine_id:int
    start_time:int
    end_time:int


def create_report(report_id:int=0):
    session = DBSession()
    file_path=''
    try:
        report=session.query(GroundReport).filter_by(id=report_id).first()
        if report:
            current_dir = os.getcwd()
            now = datetime.now()
            year_month = now.strftime("%Y-%m")
            directory_path = os.path.join(current_dir, "public","report", year_month)
            os.makedirs(directory_path, mode=0o755, exist_ok=True)  # 创建目录，如果已存在则忽略错误
            file_name = f'report_{random.randint(10000, 99999)}_{datetime.now().strftime("%Y-%m-%d")}.pdf'
            file_path = os.path.join(directory_path, file_name)
            local_path=os.path.join("report", year_month,file_name)
            http_path = local_path.replace("\\", "/")
            API_KEY='sk-1bc5d5bfc8dc42079e70ca622a03d75d'
            generator = DeepSeekPDFGenerator(API_KEY)
            prompt=report.prompt
            # 生成PDF
            content=generator.generate_content_to_pdf(prompt=prompt, output_filename=file_path,title='应力分析报告')
            if content:
                report.content = content
                report.file_path = file_path
                report.http_path = http_path
                report.update_time = int(time.time())

        session.commit()  # 提交修改
    finally:
        session.close()  # 确保会话关闭

    if os.path.exists(file_path):

        return {
            'http_path':http_path
        }
    else:
        return ''